package tool;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import server.GpcRequest;

public class StreamUtils {

	/**
	 * 将byte[] -->Object
	 * @param bytes
	 * @return
	 */
	public static byte[] serialize(Object request) {
		ByteArrayOutputStream baos = null;
		ObjectOutputStream oos = null;
		
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(request);
			return baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			//logger.error("{}", e);
		} finally {
			try {
				if(baos!=null)	
					baos.close();
				if(oos!=null) {
					oos.close();
				}
			} catch (IOException e) {
			}
		}
		return null;
	}

	/**
	 * 将byte[] -->Object
	 * @param bytes
	 * @return
	 */
	public static GpcRequest unserialize(byte[] bytes) {
		ByteArrayInputStream bais = null;
		ObjectInputStream ois = null;
		try {
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ois = new ObjectInputStream(bais);
			return (GpcRequest) ois.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if(ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(bais !=null) {
				try {
					bais.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}
